from app import ma
from .models import User
from marshmallow import fields

# 用户序列化模式，使用 SQLAlchemyAutoSchema 自动映射模型字段
class UserSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = User
        load_instance = True  # 允许反序列化回对象
        fields = ('id', 'username', 'avatar', 'created_at', 'updated_at', 'email', 'phone', 'address', 'is_admin')
    
    # 自定义时间字段序列化格式
    created_at = fields.DateTime(format='%Y-%m-%d %H:%M:%S')
    updated_at = fields.DateTime(format='%Y-%m-%d %H:%M:%S')

# 用户认证序列化模式，用于登录和注册
class UserAuthSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = User
        load_instance = True
        fields = ('id', 'username', 'email', 'password', 'is_admin')

# 创建序列化器实例
user_schema = UserSchema()  # 用于单个用户
users_schema = UserSchema(many=True)  # 用于用户列表
user_auth_schema = UserAuthSchema()  # 用于认证相关操作